package com.example.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.database.DatabaseHelper;
import com.example.pojo.Student;
import com.example.student.R;

import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentViewHolder> {
    private List<Student> studentList;
    private DatabaseHelper databaseHelper;
    // 构造函数
    public StudentAdapter(List<Student> studentList,DatabaseHelper databaseHelper) {
        this.studentList = studentList;
        this.databaseHelper = databaseHelper;
    }

    // 创建 ViewHolder
    @NonNull
    @Override
    public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_student, parent, false);
        return new StudentViewHolder(view);
    }

    // 绑定数据
    @Override
    public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) {
        Student student = studentList.get(position);
        holder.bind(student);
        // 设置删除按钮点击事件
        holder.btnDelete.setOnClickListener(v -> {
            // 从数据库中删除学生
            databaseHelper.deleteStudent(student.getStudentId());

            // 从列表中移除学生
            studentList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, studentList.size());

            // 提示删除成功
            Toast.makeText(holder.itemView.getContext(), "删除成功", Toast.LENGTH_SHORT).show();

        });
    }

    // 返回数据项数量
    @Override
    public int getItemCount() {
        return studentList.size();
    }

    // ViewHolder 类
    public static class StudentViewHolder extends RecyclerView.ViewHolder {
        private TextView textStudentId, textName, textCollegeMajor, textGradePhone;
        ImageButton btnDelete;
        public StudentViewHolder(@NonNull View itemView) {
            super(itemView);
            textStudentId = itemView.findViewById(R.id.textStudentId);
            textName = itemView.findViewById(R.id.textName);
            textCollegeMajor = itemView.findViewById(R.id.textCollegeMajor);
            textGradePhone = itemView.findViewById(R.id.textGradePhone);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }

        // 绑定学生数据
        public void bind(Student student) {
            textStudentId.setText("学号：" + student.getStudentId());
            textName.setText("姓名：" + student.getName());
            textCollegeMajor.setText("学院：" + student.getCollege() + " 专业：" + student.getMajor());
            textGradePhone.setText("年级：" + student.getGrade() + " 电话：" + student.getPhone());
        }
    }
}